package com.github.common.extend.demo.config.json.jaskson.sensitive;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.github.common.extend.demo.config.json.SensitiveInfo;

import java.io.IOException;

/**
 * @author X1993
 * @date 2022/08/12
 * @description
 */
public class SensitiveInfoSerialize extends JsonSerializer<String> implements ContextualSerializer {

    private SensitiveType type;

    public SensitiveInfoSerialize() {
    }

    public SensitiveInfoSerialize(final SensitiveType type) {
        this.type = type;
    }

    @Override
    public void serialize(final String s, final JsonGenerator jsonGenerator,
            final SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(type.sensitive(s));
    }

    @Override
    public JsonSerializer<?> createContextual(final SerializerProvider serializerProvider,
            final BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty == null) {
            // 为空直接跳过
            return serializerProvider.findNullValueSerializer(beanProperty);
        }
        if (beanProperty.getType().getRawClass() == String.class) {
            // 非 String 类直接跳过
            SensitiveInfo sensitiveInfo = beanProperty.getAnnotation(SensitiveInfo.class);
            if (sensitiveInfo == null) {
                sensitiveInfo = beanProperty.getContextAnnotation(SensitiveInfo.class);
            }
            if (sensitiveInfo != null) {
                return new SensitiveInfoSerialize(sensitiveInfo.value());
            }
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
    }
}